package com.aiolos.springboot.stepbystep.mail.impl;

import com.aiolos.springboot.stepbystep.mail.ISendMailService;
import com.aiolos.springboot.stepbystep.model.AyUser;
import com.aiolos.springboot.stepbystep.service.IAyUserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.List;

//@Service
public class SendMailServiceImpl implements ISendMailService {

    public static final Logger logger = LogManager.getLogger(SendMailServiceImpl.class);

    //JavaMailSender：邮件发送接口。在Spring Boot的Starter模块中已为此提供了自动化配置。
    //我们只需要通过注解@Autowired注入进来，即可使用
    @Autowired
    JavaMailSender mailSender;

    @Resource
    private IAyUserService ayUserService;

    //@Value：可以将application.properties配置文件中的配置设置到属性中
    @Value("${spring.mail.username}")
    private String fromUser;

    @Override
    public boolean sendMail(List<AyUser> ayUserList) {
        try{
            if(ayUserList == null || ayUserList.size() <=0) return Boolean.FALSE;
            for(AyUser user:ayUserList){
                MimeMessage mimeMessage = this.mailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
                //邮件发送方
                messageHelper.setFrom(fromUser);
                //邮件主题
                messageHelper.setSubject("今日报价");
                //邮件接收方
                messageHelper.setTo("");
                //邮件内容
                messageHelper.setText(user.getName()+",您知道吗？今天又有新消息了！");
                //发送邮件
                this.mailSender.send(mimeMessage);
            }
        }catch (Exception e){
            logger.error("SendMailServiceImpl error and user = %s",ayUserList,e);
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }
}
